본문으로 건너뛰기

23.08.24

오늘 한 일

  • gloddy 게시글 작성 페이지 구현
  • 프로그라피 어드민 페이지 회의

🤔 프로그라피 어드민 페이지

원래 랜딩 페이지 구현하기로 했는데, 추가로 어드민 페이지도 제안을 받았다.

근데 아직까지 어드민 페이지를 하겠다는 웹 개발자가 나밖에 없어서 어떻게 해야할지 고민이다.
혼자만 아니라면 참여하고 싶다..! 운영진이 못해도 한명은 무조건 데려온다고 했으니 한다고 생각해야겠다.


gloddy

useFileUpload 훅 만들기

파일을 업로드하는 로직을 커스텀 훅으로 만들었다.

컴포넌트의 UI가 변경되어도 로직을 변경할 필요가 없도록 하기 위해 커스텀 훅으로 분리했다.

import { useCallback } from 'react';

interface UseImageUploadProps {
/**
* 파일 업로드가 완료되었을 때 실행할 함수를 지정합니다.
*/
handleFileChange: (files: File[]) => void;
options?: {
/**
* 업로드할 파일의 타입을 지정합니다. (default: image/*)
*/
accept?: string;
/**
* 다중 업로드를 허용할지 여부를 지정합니다. (default: false)
*/
multiple?: boolean;
};
}

export function useFileUpload(
handleFileChange: UseImageUploadProps['handleFileChange'],
options?: UseImageUploadProps['options']
) {
const handleFileUploadClick = useCallback(() => {
const input = document.createElement('input');
input.type = 'file';
input.accept = options?.accept || 'image/*';
input.multiple = options?.multiple || false;
input.click();
input.onchange = event => {
const { files } = event.target as HTMLInputElement;
if (!files) return;

handleFileChange(Array.from(files));
};
}, [handleFileChange, options]);

return {
handleFileUploadClick,
};
}

useFileUpload 훅 사용하기

const {
field: { value, onChange },
} = useController({
name: 'images',
control,
});

const { handleFileUploadClick } = useFileUpload(files => onChange([...value, ...files]), {
multiple: true,
});

return (
// ...
<AddImageButton imageCount={value.length} onClick={handleFileUploadClick} />
);

나 같은 경우에는 react-hook-form을 사용하고 있어서, field의 value와 onChange를 받아서 사용했다.

이로서 코드 한줄로 파일 업로드 기능을 구현할 수 있게 되었다.


내일 할 일

  • 데모데이 준비